<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta
      name="viewport"
      content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"
    />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.7.1.min.js"></script>
    <title>性能检测</title>
  </head>
  <body>
    <h1>性能监控页面</h1>
    <p>这是性能监控的示例页面</p>
    <script>
      for (let i = 0; i < 100000; i++) {
        const ele = document.createElement('p');
        ele.innerText = i;
        document.body.appendChild(ele);
      }

      function performanceMonitoring() {
        // TODO timing已弃用
        const timing = window.performance.timing;

        // 计算关键性能指标
        const whiteScreenTime = timing.responseStart - timing.navigationStart;
        const firstScreenTime = timing.domContentLoadedEventEnd - timing.navigationStart;
        const domContentLoadedTime = timing.domContentLoadedEventEnd - timing.navigationStart;
        const loadTime = timing.loadEventEnd - timing.navigationStart;

        /*const navigationEntry = window.performance.getEntriesByType('navigation')[0];
        console.log(navigationEntry);
        // 计算关键性能指标
        const whiteScreenTime = navigationEntry.responseStart - navigationEntry.startTime;
        const firstScreenTime =
          navigationEntry.domContentLoadedEventEnd - navigationEntry.startTime;
        const domContentLoadedTime =
          navigationEntry.domContentLoadedEventEnd - navigationEntry.startTime;
        const loadTime = navigationEntry.loadEventEnd - navigationEntry.startTime;*/

        // 记录资源加载时间
        const resources = window.performance.getEntriesByType('resource');
        resources.forEach((resource) => {
          const resourceName = resource.name;
          const resourceLoadTime = (resource.duration / 1000).toFixed(4);
          console.log(`资源: ${resourceName}, 加载时间: ${resourceLoadTime}秒`);
        });

        // 发送性能数据到后端
        const performanceData = {
          whiteScreenTime,
          firstScreenTime,
          domContentLoadedTime,
          loadTime,
        };

        console.log(performanceData);

        // 这里使用 XMLHttpRequest 发送数据，也可以使用 fetch API
        /*const xhr = new XMLHttpRequest();
        xhr.open('POST', 'https://your-backend-url.com/performance', true);
        xhr.setRequestHeader('Content-Type', 'application/json');
        xhr.send(JSON.stringify(performanceData));*/
      }

      window.addEventListener('load', function () {
        // load 事件的触发时机是当整个页面及其所有依赖资源（如图片、样式表、脚本等）都已完全加载完成时
        // DOMContentLoaded 事件会在 HTML 文档被完全加载和解析完成之后触发，而无需等待样式表、图片等外部资源加载完成
        performanceMonitoring();
      });
    </script>
  </body>
</html>
